/**
 * @author zunqiang.Yi
 * @time 2023-10-21 14:03 PM
 * @description 数据缓存和持久化方法
 * */ 
import { PiniaPluginContext,StateTree } from 'pinia'
import { PINIA_CHCHE_KEY } from '../config/common.cfg'
import { deCodeApi, enCodeApi } from '../utils'
/** 持久化方法 */
export default function persisteStatePlugin({store}:PiniaPluginContext){
    store.$subscribe(function(_:any,_state:StateTree){
        sessionStorage.setItem(PINIA_CHCHE_KEY,enCodeApi(JSON.stringify(_state)))
    })
} 

/** 数据初始化 */
export function initState(){
    let _cache = sessionStorage.getItem(PINIA_CHCHE_KEY)
    if(!_cache){
        return {}
    }else{
        try{
            return JSON.parse(deCodeApi(_cache))
        }catch{
            return {}
        }
    }
} 